package com.gxa.hotel.sso.service.impl;

import com.aliyuncs.exceptions.ClientException;

import com.gxa.hotel.sso.service.SmsService;
import com.gxa.hotel.sso.util.SendSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * redis 为了保证高效,服务器通信完成之后应该关闭连接
 * spring在整合redis spring-boot-starter-redis中 设计了事务操作:会自动关闭
 */
@Service
@Transactional(rollbackFor = Throwable.class)
public class SmsServiceImpl implements SmsService {

    /**
     * 装配一个redisTemplate
     */
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     *
     * @param phone 用户注册的手机号
     */
    public static final String LOGIN_SMS="login_sms:";
    @Override
    public void sendLoginSms(String phone) throws ClientException {
        //一键登录 有没有账号都可以发送短信
        //发送登录 没有注册账号就不行
        //发送注册短信 注册了就不行
        //1.生成验证码(用工具类的静态方法调用)
        String sysCode= SendSms.getMsgCode();

        //生成的验证码打印在控制台(并返回给前端)用于作弊获取

        System.out.println("sysCode:"+sysCode);
        //2.服务器存储验证码并设置失效时间为30分钟
        redisTemplate.opsForValue().set(LOGIN_SMS+phone,sysCode,15, TimeUnit.MINUTES);
        //3.调用工具类发送短信给用户
        // String templateParam = "{\"getCode\":\""+msgCode+"\",
        //\"storeName\":\"淘宝直营店\", \"address\":\"阿里巴巴上海分公司
        //\",\"detail\":\"{1}号仓{2}件\"}";
        String templateParam = "{code:"+sysCode+"}";
        // 4. 短信接口返回的数据
//        SendSmsResponse response = SendSms.sendSms(phone, "SMS_204986028", templateParam);
        System.out.println("短信接口返回的数据----------------");
        System.out.println(sysCode);
//        System.out.println("Code=" + response.getCode());
//        // OK:成功
//         System.out.println("Message=" + response.getMessage());
//         System.out.println("RequestId=" + response.getRequestId());
//          System.out.println("BizId=" + response.getBizId());


    }
}
